package com.d3works.apps.crm.message;

import com.d3works.apps.base.service.app.AppBaseService;
import com.d3works.apps.base.service.message.MessageServiceBaseImpl;
import com.d3works.apps.base.service.user.UserService;
import com.d3works.apps.crm.db.Event;
import com.d3works.apps.crm.db.repo.EventRepository;
import com.d3works.apps.crm.service.config.CrmConfigService;
import com.d3works.apps.message.db.Message;
import com.d3works.apps.message.db.Template;
import com.d3works.apps.message.db.repo.MessageRepository;
import com.d3works.apps.message.service.SendMailQueueService;
import com.d3works.apps.message.service.TemplateMessageService;
import com.d3works.exception.D3worksException;
import com.d3works.inject.Beans;
import com.d3works.meta.db.repo.MetaAttachmentRepository;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import java.io.IOException;

public class MessageServiceCrmImpl extends MessageServiceBaseImpl {

  @Inject
  public MessageServiceCrmImpl(
      MetaAttachmentRepository metaAttachmentRepository,
      MessageRepository messageRepository,
      SendMailQueueService sendMailQueueService,
      UserService userService,
      AppBaseService appBaseService) {
    super(
        metaAttachmentRepository,
        messageRepository,
        sendMailQueueService,
        userService,
        appBaseService);
  }

  @Transactional(rollbackOn = {Exception.class})
  public Message createMessage(Event event)
      throws D3worksException, ClassNotFoundException, InstantiationException,
          IllegalAccessException, IOException {

    // Get template depending on event type
    Template template = null;

    switch (event.getTypeSelect()) {
      case EventRepository.TYPE_EVENT:
        template =
            Beans.get(CrmConfigService.class)
                .getCrmConfig(event.getUser().getActiveCompany())
                .getEventTemplate();
        break;

      case EventRepository.TYPE_CALL:
        template =
            Beans.get(CrmConfigService.class)
                .getCrmConfig(event.getUser().getActiveCompany())
                .getCallTemplate();
        break;

      case EventRepository.TYPE_MEETING:
        template =
            Beans.get(CrmConfigService.class)
                .getCrmConfig(event.getUser().getActiveCompany())
                .getMeetingTemplate();
        break;

      case EventRepository.TYPE_TASK:
        template =
            Beans.get(CrmConfigService.class)
                .getCrmConfig(event.getUser().getActiveCompany())
                .getTaskTemplate();
        break;

      default:
        break;
    }

    Message message = Beans.get(TemplateMessageService.class).generateMessage(event, template);

    return messageRepository.save(message);
  }
}
